package org.alfresco.repo.custom;

import java.util.Date;
import java.util.List;

import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.transaction.TransactionService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * 
 * Example of class loading the cache.
 * 
 * @author Rui Fernandes
 * 
 */
public class CacheLoaderJob implements Job {

	private SearchService searchService;
	private NodeService nodeService;
	private TransactionService transactionService;
	protected AuthenticationComponent authenticationComponent;

	public void setAuthenticationComponent(
			AuthenticationComponent authenticationComponent) {
		this.authenticationComponent = authenticationComponent;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	public void setNodeService(NodeService nodeService) {
		this.nodeService = nodeService;
	}

	public void setTransactionService(TransactionService transactionService) {
		this.transactionService = transactionService;
	}

	@Override
	public void execute(JobExecutionContext jobContext) throws JobExecutionException {
		setUp(jobContext);
		RetryingTransactionCallback<Object> txnWork = new RetryingTransactionCallback<Object>() {
			public Object execute() throws Exception {
				System.out.println("Start query!");
				Date date=new Date();
				ResultSet set=searchService.query(new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore"), SearchService.LANGUAGE_LUCENE, 
						"TYPE:\"{http://www.alfresco.org/model/content/1.0}content\"");
				List<NodeRef> nodes=set.getNodeRefs();
				for(NodeRef node:nodes){
					nodeService.getProperties(node);
				}
				System.out.println("Time to execute: "+((new Date()).getTime()-date.getTime()));
				return null;
			}
		};
		transactionService.getRetryingTransactionHelper().doInTransaction(
				txnWork);

	}

	private void setUp(JobExecutionContext jobContext) {
		nodeService = (NodeService) jobContext.getJobDetail().getJobDataMap()
				.get("nodeService");
		transactionService = (TransactionService) jobContext.getJobDetail()
				.getJobDataMap().get("transactionService");
		authenticationComponent = (AuthenticationComponent) jobContext
				.getJobDetail().getJobDataMap().get("authenticationComponent");
		searchService = (SearchService) jobContext.getJobDetail()
				.getJobDataMap().get("searchService");
		authenticationComponent.setSystemUserAsCurrentUser();

	}
}
